﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using AutodeskInventorInterfaces.Extend;
using AutodeskInventorInterfaces.Model.Exceptions;
using AutodeskInventorInterfaces.Service;
using Inventor;

namespace AutodeskInventorInterfaces.Model.Translators
{
  /// <summary>
  /// 草图格式转换器
  /// </summary>
  public class InventorTranslatorSketch : InventorTranslator
  {
    public InventorTranslatorSketch() : base()
    {
      ClassId = "";
      Name = "转换器: Sketch";
      Ext = "png";
    }

    public override InventorTranslator SetOptions(NameValueMap options)
    {
      options.Value["All_Color_AS_Black"] = 1;
      options.Value["Sheet_Range"] = PrintRangeEnum.kPrintAllSheets;
      return this;
    }

    public override object Translate(dynamic partDoc, string fileName, ExportFileTypes exportFileTypes)
    {
      partDoc.Activate();
      var mainView = partDoc.Views[1];
      if (mainView != null)
      {
        mainView.WindowState = WindowsSizeEnum.kMaximize; //必须将主视图窗口最大化
        Thread.Sleep(1000); // 延时2秒确保窗口已最大化
        if (partDoc.ComponentDefinition.Sketches.Count == 0)
        {
          throw InventorException.文档格式转换失败.Create(Name).SetDetail("草图加载失败！");
        }
        var sketchs = partDoc.ComponentDefinition.Sketches;
        var sketchImages = new List<string>();
        var camera = mainView.Camera;
        var bgColor = InventorApplication.Application.TransientObjects.CreateColor(0, 0, 0); // 图纸背景色
        foreach (PlanarSketch sketch in sketchs)
        {
          sketch.Edit();
          var sketchImageFile = $"{InventorApplication.PartTempPath}part_{Guid.NewGuid()}.png";
          var eyePoint = sketch.OriginPointGeometry;
          eyePoint.TranslateBy(sketch.PlanarEntityGeometry.Normal.AsVector());
          camera.Eye = eyePoint;
          camera.Target = sketch.OriginPointGeometry;
          camera.UpVector = sketch.AxisEntityGeometry.Direction;
          camera.Fit();
          camera.ApplyWithoutTransition();
          camera.SaveAsBitmap(sketchImageFile, mainView.Width, mainView.Height, bgColor);
          sketch.ExitEdit();
          sketchImages.Add(sketchImageFile.ToRelativePath());
        }
        return sketchImages;
      }
      else
      {
        throw InventorException.文档格式转换失败.Create(Name).SetDetail("零部件主视图不存在！");
      }
    }
  }
}